from django.shortcuts import HttpResponse
import cmdb.api.http_result as hh
from cmdb import models
import uuid
from cmdb.util import time
from django.conf import settings
import json
from cmdb.util import http_util as hu
from cmdb.api.session import session_set
from cmdb.api.session import session_get
from cmdb.api.session import session_clear


def update_token(req):
    token = req.POST.get('token', None)
    session_set(token, 'last_time', time.current_timestamp())
    invalid_time = time.current_timestamp() + settings.TOKEN_INVALID_DURATION

    user_id = session_get(token, 'user_id')

    if not user_id:
        print('user_id is none, please check it now!!!')
    else:
        # 保存到数据库
        try:
            ut = models.UserToken.objects.get(user_id=user_id)
            ut.token = token
            ut.invalid_time = invalid_time
            ut.save()

        except:
            models.UserToken.objects.create(user_id=user_id, token=token, invalid_time=invalid_time)


def logout(req):
    token = req.POST.get('token', None)
    session_clear(token)

    if token:
        try:
            t = models.UserToken.objects.get(token=token)
            t.delete()
        except:
            pass

    return hh.resp_result(1, hh.RESULT_SUCCESS)


def login(req):

    try:
        data = hu.json_obj(req)[0]
        token = req.POST.get('token', 'null')
        if data:
            wx_id = data.get('open_id', None)
            if not wx_id:
                return hh.resp_result(0, 'open_id is not found')

            name = data.get('name', '')
            head = data.get('head', '')

            try:
                user = models.User.objects.get(wx_id=wx_id)
                user.name = name
                user.head = head
                user.save()

                session_set(token, 'user_id', user.id)

            except:
                uid = uuid.uuid1().__str__()
                result = models.User.objects.update_or_create(id=uid, wx_id=wx_id, name=name, head=head)
                if not result[1]:
                    return hh.resp_result(0, hh.RESULT_FAIL, result)

                session_set(token, 'user_id', uid)


            return hh.resp_result(1, hh.RESULT_SUCCESS)
        else:
            return hh.resp_result(0, 'data format error')

    except BaseException as error:
        print(error)
        return HttpResponse(hh.resp_result(0, 'data format error', {hh.ERROR_INFO: error.__str__()}))

def my_balance(req):
    token = req.POST.get('token', 'null')
    user_id = session_get(token, 'user_id')
    if not user_id:
        return hh.resp_result(0, 'user_id is null')
    else:
        balance = 0
        try:
            bal = models.Balance.objects.get(user_id=user_id)
            balance = bal.balance
        except:
            pass
        return HttpResponse(hh.result(1, hh.RESULT_SUCCESS, {'money': balance}))